package com.itouch.bracelet.bluetooth;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.itouch.bracelet.R;
import com.itouch.bracelet.activity.MMessageListActivity;
import com.itouch.bracelet.bean.Child;
import com.itouch.bracelet.cache.UserCache;
import com.itouch.bracelet.diseaseinfo.Constants;
import com.itouch.util.JsonAndPhpUtil;

/**
 * 

* @ClassName: BluetoothHandler 

* @Description: TODO(蓝牙消息处理中心) 

* @author sunshineHu hucx@itouch.com.cn

* @date 2015年1月16日 上午10:37:41 

*
 */
public class BluetoothHandler extends Handler{

	
	public static final String ACTION_DATA="ACTION_DATA";
	public static final String ACTION_STATUS="ACTION_STATUS";
	
	private WeakReference<Context> contextReference;//弱引用

	private ExecutorService es;//线程池
	
	private long lastUpdate;
	
	public BluetoothHandler(Context c) {
		// TODO Auto-generated constructor stub
		contextReference=new WeakReference<Context>(c);
		es=Executors.newCachedThreadPool();//创建线程池
		

		// init status
		if (BluetoothValue.INSTANCE.lowEnergyStatus == null) {

			SharedPreferences sp = contextReference.get().getSharedPreferences("Bluetooth",
					Context.MODE_PRIVATE);
			BluetoothValue.INSTANCE.temperatureStatus = sp.getBoolean(
					"temperature", true);
			BluetoothValue.INSTANCE.lowEnergyStatus = sp.getBoolean(
					"lowenergy", true);
			BluetoothValue.INSTANCE.lostStatus = sp.getBoolean("lost", true);

			BluetoothValue.INSTANCE.braceletWarnStatus = false;
		}
	}

	@Override
	public void handleMessage(Message msg) {
		// TODO Auto-generated method stub
		super.handleMessage(msg);
		if(contextReference.get()==null){
			return;
		}
		//发送状态广播
		if(msg.what!=BluetoothConstants.DATA_RECEIVE){
			
			Intent in=new Intent();
			in.setAction(ACTION_STATUS);
			in.putExtra("status", msg.what);
			if(msg.obj!=null){
				//包含错误信息的或其他信息
				if(msg.what==BluetoothConstants.MESSAGE_CONNECT_FAILED){
					Exception e=(Exception) msg.obj;
					in.putExtra("error", e.getMessage());
				}
			}
			contextReference.get().sendBroadcast(in);
			
		}
		
		switch(msg.what){
			
		case BluetoothConstants.DATA_RECEIVE:
			//接收到数据
			if(contextReference.get()!=null){//外部引用不为空
				List<BluetoothPacket> lists;
				byte[] content=(byte[]) msg.obj;
				try {
					lists=BluetoothUtil.unpackData(content);
				} catch (Exception e) {
					// TODO: handle exception
					return;
				}
				for(BluetoothPacket packet:lists){
					//将数据上传到服务器
					if(packet.getType()!=null){
						switch(packet.getType()){
						case DATA_STEP_MOTHER:
							
							int steps=BluetoothUtil.getSteps(packet);
							
							List<NameValuePair> mylists1=new ArrayList<NameValuePair>();
							mylists1.add(new BasicNameValuePair("type", "2"));
							mylists1.add(new BasicNameValuePair("customerId", UserCache.getOauth(contextReference.get()).getUserId()));
							mylists1.add(new BasicNameValuePair("creator", UserCache.getOauth(contextReference.get()).getUserId()));
							mylists1.add(new BasicNameValuePair("steps", steps+""));
							mylists1.add(new BasicNameValuePair("customerType", "1"));//1大人 2儿童
							UploadData ud1=new UploadData(mylists1, "/mobi/sports/save");
							
							if(System.currentTimeMillis()-lastUpdate>1000){
								es.execute(ud1);
								lastUpdate=System.currentTimeMillis();
							}
							
							break;
						case DATA_STEP_CHILD:
							
							int childSteps=BluetoothUtil.getSteps(packet);
							
							Child mychild=BluetoothUtil.getChild(UserCache.getOauth(contextReference.get()), packet);
							if(mychild!=null){
								//存在该孩子
								List<NameValuePair> mylists3=new ArrayList<NameValuePair>();
								mylists3.add(new BasicNameValuePair("type", "2"));
								mylists3.add(new BasicNameValuePair("customerId", mychild.getId()));
								mylists3.add(new BasicNameValuePair("creator", UserCache.getOauth(contextReference.get()).getUserId()));
								mylists3.add(new BasicNameValuePair("steps", childSteps+""));
								mylists3.add(new BasicNameValuePair("customerType", "2"));//1大人 2儿童
								UploadData ud3=new UploadData(mylists3, "/mobi/sports/save");
								
								if(System.currentTimeMillis()-lastUpdate>1000){
									es.execute(ud3);
									lastUpdate=System.currentTimeMillis();
								}
								
							}
							//Log.e("CHILD STEP", packet.getRaw()+"");
							break;
						case DATA_TEMPERATURE:
							if(BluetoothValue.INSTANCE.temperatureStatus){
								//体温数据
								
								Child child=BluetoothUtil.getChild(UserCache.getOauth(contextReference.get()), packet);
								
								if(child!=null){
								
									List<NameValuePair> mylists2=new ArrayList<NameValuePair>();
									mylists2.add(new BasicNameValuePair("name", child.getName()));
									mylists2.add(new BasicNameValuePair("customerId", child.getId()));
									int temp=((packet.getData()[4] & 0xFF) <<8) | (packet.getData()[5] & 0xFF);//byte转int
									mylists2.add(new BasicNameValuePair("temperature", temp/10+""));
									UploadData ud2=new UploadData(mylists2, "/mobi/health/AddHealth");
								
									if(System.currentTimeMillis()-lastUpdate>1000){
										es.execute(ud2);
										lastUpdate=System.currentTimeMillis();
									}
									
								}
							}
							break;
						case DATA_STATUS:
							//读取手环发过来的状态包
							byte stepStatus=packet.getData()[2];
							if(stepStatus==(byte)0){
								BluetoothValue.INSTANCE.stepStatus=false;
							}else{
								BluetoothValue.INSTANCE.stepStatus=true;
							}
							byte takeIncorrectStatus=packet.getData()[3];
							if(takeIncorrectStatus==(byte)0){
								BluetoothValue.INSTANCE.takeIncorrectStatus=false;
							}else{
								BluetoothValue.INSTANCE.takeIncorrectStatus=true;
							}
							byte outOfRangeStatus=packet.getData()[5];
							if(outOfRangeStatus==(byte)0){
								BluetoothValue.INSTANCE.braceletWarnStatus=false;
							}else{
								BluetoothValue.INSTANCE.braceletWarnStatus=true;
							}
							break;
						case WARN_LOST:
							if(BluetoothValue.INSTANCE.lostStatus){
								setMsgNotification("小爱报警", "您的设备已脱落，请检查",0);
							}
							break;
						case WARN_LOW_ENERGY:
							if(BluetoothValue.INSTANCE.lowEnergyStatus){
								setMsgNotification("小爱报警", "您的设备电量不足，请及时充电",1);
							}
							break;
						case WARN_OUT_OF_RANGE_BABY:
							if(BluetoothValue.INSTANCE.outOfRangeStatus){
								setMsgNotification("小爱报警", "您的设备已超出连接范围",2);
							}
							break;

						case WARN_OUT_OF_RANGE_CHILD:
							if(BluetoothValue.INSTANCE.outOfRangeStatus){
								setMsgNotification("小爱报警", "您的设备已超出连接范围",2);
							}
							break;
						case WARN_TAKE_INCORRECT:
							setMsgNotification("小爱报警", "您抱错了孩子",3);
							//报警数据
							List<NameValuePair> mylists2=new ArrayList<NameValuePair>();
							mylists2.add(new BasicNameValuePair("localModel","1"));
							mylists2.add(new BasicNameValuePair("content","孩子抱错警报"));
							mylists2.add(new BasicNameValuePair("title","警报信息"));
							mylists2.add(new BasicNameValuePair("returnCode","200"));
							mylists2.add(new BasicNameValuePair("msgType","3"));
							mylists2.add(new BasicNameValuePair("receiver", UserCache.getOauth(contextReference.get()).getUserId()));
							mylists2.add(new BasicNameValuePair("receiverN", UserCache.getOauth(contextReference.get()).getUserName()));
							UploadData ud=new UploadData(mylists2, "/mobi/rongMsg/AddRongMsg");
							es.execute(ud);
							break;
						case WARN_TAKE_CORRECT:
							setMsgNotification("小爱报警", "您抱对了孩子",3);
							break;
						case WARN_STEAL:
							setMsgNotification("小爱报警", "您的孩子被抱走，请查看",3);
							break;
						}
					}
					Intent in=new Intent();
					in.setAction(ACTION_DATA);
					in.putExtra("packet", packet);
					contextReference.get().sendBroadcast(in);
				}
			}
			break;
		case BluetoothConstants.MESSAGE_DEVICE_UNBOND:
			Toast.makeText(contextReference.get(), "您的设备尚未绑定，请在通知栏或弹出窗口中确认绑定！", Toast.LENGTH_SHORT).show();
			break;
		case BluetoothConstants.RECEIVE_ERROR:
			//接收线程错误
			
			break;
		case BluetoothConstants.SEND_ERROR:
			//发送错误
			
			break;
		case BluetoothConstants.HANDLE_ERROR:
			//处理消息线程错误
			
			break;
		case BluetoothConstants.MESSAGE_CONNECT_FAILED:
			//连接失败
			
			break;
		case BluetoothConstants.MESSAGE_CONNECT_SUCCESS:
			//连接成功
			
			break;
		}
		
	}
	
	

	
	//上传数据
	class UploadData implements Runnable{

		private List<NameValuePair> lists;
		private String url;
		
		public UploadData(List<NameValuePair> lists,String url) {
			// TODO Auto-generated constructor stub
		
			this.lists=lists;
			this.url=url;
			
		}
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			String ss = JsonAndPhpUtil.postHttpData(Constants.URL+url, lists, contextReference.get());
		}
		
	}
	
	
	
	
	
	
	//显示通知
	private void setMsgNotification(String title, String message,int notifyId) {

		// 创建一个NotificationManager的引用

		NotificationManager notificationManager = (NotificationManager)

		contextReference.get().getSystemService(android.content.Context.NOTIFICATION_SERVICE);

		// 定义Notification的各种属性

		Notification notification = new Notification(R.drawable.logo,
				"小爱", System.currentTimeMillis());

		notification.flags |= Notification.FLAG_AUTO_CANCEL;

		notification.flags |= Notification.FLAG_SHOW_LIGHTS;

		notification.defaults = Notification.DEFAULT_LIGHTS;

		notification.ledARGB = Color.BLUE;

		notification.ledOnMS = 5000; // 闪光时间，毫秒

		CharSequence contentTitle = title; // 通知栏标题

		CharSequence contentText = message; // 通知栏内容

		Intent notificationIntent = new Intent();

		notificationIntent.setClass(contextReference.get(),
				MMessageListActivity.class);

		PendingIntent contentItent = PendingIntent.getActivity(contextReference.get(), 0,
				notificationIntent, 0);

		notification.setLatestEventInfo(contextReference.get(), contentTitle, contentText,
				contentItent);

		// 把Notification传递给NotificationManager

		notificationManager.notify(notifyId, notification);

	}

	

	
}
